'''
Created on May 2, 2010

@author: william
'''

import os

# This function allows commands to be parsed from within Python.
def command(cmd):
    command = os.popen(cmd)
    output = command.readlines()
    command.close()
    return output

# This function uses the "free" system command in order to identify
# how much memory the system is using and it's total available.
# We use "os.popen" to run the command, and give us the output
# so we can manipulate it.
def memory():
    mem = {}
    mem['Total'] = command("free | awk '/Mem/{print $2}'") # We pipe the output into
    mem['Free'] =  command("free | awk '/Mem/{print $4}'") # awk to parse the output
    mem['Used'] = command("free | awk '/Mem/{print $3}'") # of the "free" command.

    swap = {}
    swap['Total'] = command("free | awk '/Swap/{print $2}'")
    swap['Free'] =  command("free | awk '/Swap/{print $4}'")
    swap['Used'] = command("free | awk '/Swap/{print $3}'")
    
    memory = {}
    memory['Memory'] = mem
    memory['Swap'] = swap
    return memory # Returns a dictionary with both the swap and memory.

# This function uses the "df -h" command to get currently mounted filesystems
# and their disk space.
def disk():
    disk = {}
    diskcmd = command('df -h')[1:] # We start from index 1 to cut out the header
    for line in diskcmd:
        disk[line.split()[0]] = {'Size':line.split()[1], 
                                 'Used':line.split()[2],
                                 'Avail':line.split()[3],
                                 'Use%':line.split()[4],
                                 'Mounted':line.split()[5]}
    return disk # Outputs everything into a dictionary.

# Lists installed packages on the system.
def installed_pkg():
    packages = {}
    output = command("aptitude -F '%?p %?V' search '~i'") # Grabs all installed pkgs
    for line in output:
        packages[line.split()[0]] = line.split()[1] # {'pkg name': 'version'}
    return packages
